<template>
  <div class="container">
    <!-- 主表格只显示id、表名和说明 -->
    <el-table :data="tableList" border style="width: 100%">
      <el-table-column
        prop="id"
        label="序号"
        type="index"
        align="center"
        width="100"
      ></el-table-column>
      <el-table-column
        prop="tableName"
        label="表名"
        align="center"
      ></el-table-column>
      <el-table-column
        prop="tableComment"
        label="说明"
        align="center"
      ></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showEditDialog(row)"
            >编辑</el-button
          >
          <el-button type="danger" size="small" @click="deleteTable(row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 返回上一页按钮 -->
    <el-button style="margin-top: 40px" type="primary" @click="goBack"
      >返回</el-button
    >

    <!-- 编辑对话框，显示字段集合 -->
    <el-dialog
      v-model="dialogVisible"
      title="编辑表结构"
      width="70%"
      destroy-on-close
    >
      <el-button
        type="success"
        size="primary"
        @click="addField"
        style="margin-bottom: 20px"
        >新增字段</el-button
      >
      <el-table
        ref="fieldTable"
        :data="currentFields"
        border
        :key="Date.now()"
        max-height="400"
        class="custom-scrollbar"
      >
        <el-table-column prop="name" label="字段名" align="center">
          <template #default="{ row }">
            <el-input v-model="row.name"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="type" label="类型" align="center">
          <template #default="{ row }">
            <el-select v-model="row.type">
              <el-option value="INT">INT</el-option>
              <el-option value="VARCHAR">VARCHAR</el-option>
              <el-option value="TEXT">TEXT</el-option>
              <el-option value="DATETIME">DATETIME</el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="length" label="长度" align="center">
          <template #default="{ row }">
            <el-input-number v-model="row.length" :min="0"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="属性">
          <template #default="{ row }">
            <el-checkbox v-model="row.isKey">主键</el-checkbox>
            <el-checkbox v-model="row.isAddId">自增</el-checkbox>
            <el-checkbox v-model="row.isNull">允许NULL</el-checkbox>
          </template>
        </el-table-column>
        <el-table-column label="注释" align="center">
          <template #default="{ row }">
            <el-input v-model="row.comment"></el-input>
          </template>
        </el-table-column>
        <!-- 新增删除按钮 -->
        <el-table-column label="操作" align="center">
          <template #default="{ row }">
            <el-button type="danger" @click="deleteField(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { nextTick } from "vue";
import { ref, onMounted } from "vue";
import axios from "axios";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";

const router = useRouter();
const tableList = ref([]);
const dialogVisible = ref(false);
const currentFields = ref([]);
const currentTableId = ref(null);
// 获取当前选择的表名
const currentTableName = ref("");

// 获取表格列表数据
const fetchTableList = async () => {
  try {
    const response = await axios.get(
      "http://localhost:8080/api/dbtable/getTable"
    );
    console.log("API完整响应:", response.data);

    // 解析result字段
    const resultData = JSON.parse(response.data.result);

    tableList.value = resultData.map((item) => ({
      id: item.id,
      tableName: item.tableName,
      tableComment: item.tableComment,
      // 解析fieldContent字符串为数组
      fieldContent:
        typeof item.fieldContent === "string"
          ? JSON.parse(item.fieldContent)
          : item.fieldContent || [],
    }));

    console.log("处理后的表格数据:", tableList.value);
  } catch (error) {
    console.error("获取表格列表失败:", error);
  }
};
// 解析字段内容
const parseFieldContent = (content) => {
  if (!content) return [];
  try {
    return typeof content === "string" ? JSON.parse(content) : content;
  } catch (e) {
    console.error("解析字段内容失败:", e);
    return [];
  }
};
// 显示编辑对话框
const showEditDialog = (row) => {
  isAddingField.value = false;
  isSaving.value = false;
  try {
    currentTableName.value = row.tableName;
    currentTableId.value = row.id;

    const rawFields = parseFieldContent(row.fieldContent);

    // 确保字段有默认值
    currentFields.value = rawFields.map((field) => ({
      name: field.fieldName || "",
      type: field.fieldType || "VARCHAR",
      length: field.fieldLength || 0,
      isKey: field.isKey == "1",
      isAddId: field.isAddId == "1",
      isNull: field.isNull == "1",
      comment: field.fieldComment || "",
    }));

    // 使用nextTick确保DOM更新完成后再显示对话框
    nextTick(() => {
      dialogVisible.value = true;
    });
  } catch (error) {
    console.error("打开编辑对话框失败:", error);
    ElMessage.error("打开编辑对话框失败");
  }
};

// 保存编辑
const saveEdit = async () => {
  try {
    isSaving.value = true;

    let newFields = currentFields.value.filter((field) => field.isNew);

    const field = newFields[0];

    const Field = {
      fieldName: field.name,
      fieldType: field.type,
      fieldLength: field.length,
      isKey: field.isKey ? "1" : "0",
      isAddId: field.isAddId ? "1" : "0",
      isNull: field.isNull ? "1" : "0",
      fieldComment: field.comment,
    };
    console.log("编辑字段:", newFields);
    console.log("新增字段:", Field);

    // 只发送新增字段
    const res = await axios.post(
      `/api/dbtable/newUpdateTable?tableName=${currentTableName.value}`,
      Field // 仅发送 Field 作为请求体
    );

    console.log("保存结果:", res);

    if (res.status == 200) {
      ElMessage.success("添加成功");
    }

    // dialogVisible.value = false;
    fetchTableList(); // 刷新列表
  } catch (error) {
    console.error("保存失败:", error);
  } finally {
    isSaving.value = false;
    isAddingField.value = false;
  }
};
const goBack = () => {
  router.back();
};

const deleteField = async (row) => {
  // 提示用户是否删除
  ElMessageBox.confirm("确定删除该字段吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await axios.post(
          `http://localhost:8080/api/dbtable/updateTable`,
          null,
          {
            params: {
              tableName: currentTableName.value,
              fieldName: row.name,
            },
          }
        );
        // 延迟更新
        await nextTick();
        // dialogVisible.value = false;
        // 从 currentFields 中移除被删除的字段
        currentFields.value = currentFields.value.filter(
          (field) => field.name !== row.name
        );
        fetchTableList(); // 刷新列表
        ElMessage.success("删除成功");
      } catch (error) {
        console.error("保存失败:", error);
      }
      console.log("待删除字段:", row);
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "已取消删除",
      });
    });
};
const isAddingField = ref(false); // 是否正在新增字段
const isSaving = ref(false); // 是否正在保存
const fieldTable = ref(null);
const addField = () => {
  if (isAddingField.value || isSaving.value) return; // 防止重复点击
  isAddingField.value = true; // 标记为正在新增字段

  currentFields.value.push({
    name: "",
    type: "VARCHAR",
    length: 50,
    isKey: false,
    isAddId: false,
    isNull: false,
    comment: "",
    isNew: true, // 标记为新增字段
  });
  // 使用nextTick确保DOM更新
  nextTick(() => {
    // 通过ref获取表格实例
    const tableEl = fieldTable.value?.$el;
    if (!tableEl) return;

    // 精准定位滚动容器
    const scrollBody = tableEl.querySelector(".el-table__body-wrapper");
    if (scrollBody) {
      // 使用动画实现平滑滚动
      scrollBody.scrollTo({
        top: scrollBody.scrollHeight,
        behavior: "smooth",
      });
    }
    isAddingField.value = false;
  });
};

/** 
  删除表
**/

const deleteTable = async (id) => {
  ElMessageBox.confirm("此操作将永久删除该表, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      const res = await axios.post(
        `http://localhost:8080/api/dbtable/deleteTable`,
        null,
        {
          params: {
            id: id,
          },
        }
      );
      if (res.status == 200) {
        ElMessage.success("删除成功");
        fetchTableList();
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

onMounted(() => {
  fetchTableList();
});
</script>
<style scoped lang="scss">
.container {
  margin: 20px 50px;
}
</style>